import Vue from 'vue'
import Router from 'vue-router'
import defaultroutes from './routers'
import store from '@/store'
import ViewUI from 'view-design'
import { setToken, getToken, setTitle } from '@/libs/util'

import { defaultNames } from '@/libs/router-util'
import config from '@/config'
const { homeName } = config
Vue.use(Router)
const router = new Router({
  routes: defaultroutes,
  mode: 'history'
})
const LOGIN_PAGE_NAME = 'login'
router.beforeEach((to, from, next) => {
 
  ViewUI.LoadingBar.start()
 
  const token = getToken()  
  if (to.path.indexOf('public') > -1) {
    next() // 跳转
  } else {
    if (!token && to.name !== LOGIN_PAGE_NAME) {
      // 未登录且要跳转的页面不是登录页
      next({
        name: LOGIN_PAGE_NAME // 跳转到登录页
      })
    } else if (!token && to.name === LOGIN_PAGE_NAME) {
      // 未登录且要跳转的页面是登录页
      next() // 跳转
    } else {
      if (store.state.user.hasGetInfo) {
        if (token && to.name === LOGIN_PAGE_NAME) {
          // 已登录且要跳转的页面是登录页
          next({
            name: 'home' // 跳转到homeName页
          })
        } else {
          next()
          var routerNames = store.state.app.routernameList
          if (routerNames.indexOf(to.name) > -1 || defaultNames.indexOf(to.name) > -1) {
            next()
          } else {
            next({ replace: true, name: 'error_401' })
          }
        }
      } else {
        store.dispatch('GetUserInfo').then(res => { 
          if (res.StatusCode == 200) {
            next({ ...to, replace: true })
          } else {  
            setToken('')
           
            next({
              name: LOGIN_PAGE_NAME // 跳转到登录页
            }) 
          }
        }).catch((e) => {  
          console.log(e)
           setToken('')
        
          next({
            name: LOGIN_PAGE_NAME // 跳转到登录页
          })
          
        })
      }
    }
  }
})

router.afterEach(to => {
  setTitle(to, router.app)
  ViewUI.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
